package com.doyens.item.service;

import com.doyens.common.pojo.PageResult;
import com.doyens.item.mapper.BrandMapper;
import com.doyens.item.pojo.Brand;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.security.auth.login.CredentialException;
import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;


    public PageResult<Brand> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();

        //判断key是否有数据
        if (StringUtils.isNotBlank(key)){//不为空

            criteria.andLike("name", "%"+key+"%").orEqualTo("letter",key);
        }
        //添加分页条件
        PageHelper.startPage(page,rows);
        //添加排序字段
        if(StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy+"  "+(desc ? "desc": "asc"));
        }
        //查询数据库
        List<Brand> brands = this.brandMapper.selectByExample(example);
        //包装分页结果
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }

    public void saveBrand(Brand brand, List<Long> cids) {
        this.brandMapper.insertSelective(brand);
        //保存到桥表
        cids.forEach(cid ->{
            this.brandMapper.saveBrandAndCategoryId(brand.getId(),cid);
        });


    }

    public List<Brand> queryBrandByCid(Long cid) {
        return this.brandMapper.selectBrandByCid(cid);
    }

    //根据品牌id查询品牌
    public Brand queryBrandById(Long id) {
        return this.brandMapper.selectByPrimaryKey(id);
    }
}
